//
//  MGPunchController.m
//  MoneyGoal_iOS
//
//  Created by yyb on 2022/7/29.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGPunchController.h"
#import "MGAccountController.h"
#import "MGAccountsController.h"
#import "MGCategoryController.h"
#import "MGCategoriesController.h"

#import "MGReceiptMoneyCell.h"
#import "MGReceiptRemarkCell.h"
#import "MGReceiptKeyBoardView.h"

#import "MGBaseBorderDetailCell.h"

#import "NSString+ReceiptAdd.h"

@interface MGPunchController ()
@property (nonatomic, strong) MGReceiptKeyBoardView *keyboardView;

@property (nonatomic, copy) NSString *calculateString;
@property (nonatomic) BOOL shouldOpenCategory, shouldOpenAccount;

@end

@implementation MGPunchController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.updateModel) {
        self.dataModel = [MGReceiptModel yy_modelWithJSON:self.updateModel.yy_modelToJSONObject];
        if (self.dataModel.receiptType == MGReceiptTypePunch) {
            self.dataModel.savedMoney = self.updateModel.savedMoney ? : self.updateModel.shouldSaveMoney;
            self.calculateString = self.dataModel.savedMoney ? self.dataModel.savedMoney.stringValue : self.dataModel.shouldSaveMoney.stringValue;
        }
    } else {
        self.dataModel = [[MGReceiptModel alloc] init];
    }
    
    if (self.dataModel.categoryUniqueId == 0) {
        self.dataModel.categoryUniqueId = [MGCategoryAccessor.shared getStandardCategoryModel].uniqueId;
    }
    if (self.dataModel.accountUniqueId == 0) {
        self.dataModel.accountUniqueId = [MGAccountAccessor.shared getStandardAccountModel].uniqueId;
    }
    if (self.dataModel.actualSaveTime == 0) {
        self.dataModel.actualSaveTime = [NSDate date].timeIntervalSince1970;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (self.shouldOpenCategory) {
        [self handleSelectCategory];
        self.shouldOpenCategory = NO;
    }
    
    if (self.shouldOpenAccount) {
        [self handleSelectAccount];
        self.shouldOpenAccount = NO;
    }
}

- (void)beginConfigViewAction {
    [super beginConfigViewAction];
    
    // 计算器
    self.keyboardView = [[MGReceiptKeyBoardView alloc] init];
    [self.view addSubview:self.keyboardView];
    [self.keyboardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(225 + 80 + 2 + 20 + [UIDevice safeAreaInsetsBottom]);
    }];

    @weakify(self);
    self.keyboardView.stringChangedBlock = ^(NSString *text) {
        @strongify(self);
        [self handleCalculateWithString:text];
    };
    self.keyboardView.dismissTapedBlock = ^{
        @strongify(self);
        [self handleKeyboardTransform];
    };
    self.keyboardView.completeTapedBlock = ^{
        @strongify(self);
//        if (self.updateModel) {
//            [self handleComplete];
//        } else {
//            [self handleReceiptAction];
//        }
    };
}

//// 添加、修改收支记录
//- (void)handleReceiptAction {
//    if (self.dataModel.shouldSaveMoney.floatValue == 0) {
//        [YYBAlertView showAlertViewWithStatusString:@"请输入金额"];
//    } else if (self.dataModel.remark.length > 150) {
//        [YYBAlertView showAlertViewWithStatusString:@"备注长度不能大于150个字符"];
//    } else {
//        @weakify(self);
//        [MGReceiptManager.shared createReceiptModel:self.dataModel completeBlock:^{
//            @strongify(self);
//            if (self.updateSuccBlock) {
//                self.updateSuccBlock();
//            }
//            [self.navigationController popViewControllerAnimated:YES];
//        }];
//
//
//    }
//}
//
//// 打卡的时候完成
//- (void)handleComplete {
//    if (self.dataModel.shouldSaveMoney.floatValue == 0) {
//        [YYBAlertView showAlertViewWithStatusString:@"请输入金额"];
//    } else if (self.dataModel.remark.length > 150) {
//        [YYBAlertView showAlertViewWithStatusString:@"备注长度不能大于150个字符"];
//    } else {
//        @weakify(self);
//        // 打卡
//        [MGReceiptManager.shared punchReceiptModel:self.dataModel money:self.dataModel.savedMoney completeBlock:^{
//            @strongify(self);
//            if (self.updateSuccBlock) {
//                self.updateSuccBlock();
//            }
//            [self.navigationController popViewControllerAnimated:YES];
//        }];
//    }
//}

// 选择账户
- (void)handleSelectAccount {
    @weakify(self);
    MGAccountModel *accountModel = [MGAccountAccessor.shared getAccountModelWithUniqueId:self.dataModel.accountUniqueId];
    if (!accountModel) {
        accountModel = [MGAccountAccessor.shared getStandardAccountModel];
    }
    
    [MGAlertView showAccountsAlertViewWithSelectModel:accountModel selectedBlock:^(MGAccountModel * _Nonnull dataModel) {
        @strongify(self);
        self.dataModel.accountUniqueId = dataModel.uniqueId;
        [self.tableView reloadData];
    } selectActionBlock:^(MGAlertViewActionType type) {
        @strongify(self);
        if (type == MGAlertViewActionTypeCreate) {
            self.shouldOpenAccount = YES;
            [self createAccount];
        } else if (type == MGAlertViewActionTypeList) {
            self.shouldOpenAccount = YES;
            [self getIntoAccountList];
        }
    }];
}

// 选择类型
- (void)handleSelectCategory {
    @weakify(self);
    // 获取当前的选中的类别
    MGCategoryModel *categoryModel = [MGCategoryAccessor.shared getCategoryModelWithUniqueId:self.dataModel.categoryUniqueId];
    if (!categoryModel) {
        categoryModel = [MGCategoryAccessor.shared getStandardCategoryModel];
    }
    
    [MGAlertView showCategoriesAlertViewWithSelectModel:categoryModel selectedBlock:^(MGCategoryModel * _Nonnull dataModel) {
        @strongify(self);
        self.dataModel.categoryUniqueId = dataModel.uniqueId;
        [self.tableView reloadData];
    } selectActionBlock:^(MGAlertViewActionType type) {
        @strongify(self);
        if (type == MGAlertViewActionTypeCreate) {
            self.shouldOpenCategory = YES;
            [self createCategory];
        } else if (type == MGAlertViewActionTypeList) {
            self.shouldOpenCategory = YES;
            [self getIntoCategoryList];
        }
    }];
}

// 选择日期
- (void)handleSelectDate {
    @weakify(self);
    NSDate *selectDate = [NSDate dateWithTimeIntervalSince1970:self.dataModel.actualSaveTime];
    [MGAlertView showReceiptDateAlertViewWithDate:selectDate dateOrTime:self.dataModel.dateOrTime dateSelectBlock:^(NSDate * _Nonnull date, BOOL dateOrTime) {
        @strongify(self);
        self.dataModel.dateOrTime = dateOrTime;
        self.dataModel.actualSaveTime = date.timeIntervalSince1970;
        [self.tableView reloadData];
    }];
}

- (void)createAccount {
    [YYBViewRouter openOnClass:[MGAccountController class]];
}

- (void)getIntoAccountList {
    [YYBViewRouter openOnClass:[MGAccountsController class]];
}

- (void)createCategory {
    [YYBViewRouter openOnClass:[MGCategoryController class]];
}

- (void)getIntoCategoryList {
    [YYBViewRouter openOnClass:[MGCategoriesController class]];
}

- (NSArray<NSString *> *)dequeueCellIdentifiers {
    return @[@"MGReceiptMoneyCell",@"MGReceiptRemarkCell",@"MGBaseBorderDetailCell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 100;
    }
    return 55;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        MGReceiptMoneyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGReceiptMoneyCell"];

        BOOL isPunched = self.dataModel.actualSaveTime != 0;
        [cell configViewWithTitleValue:self.calculateString receiptType:self.dataModel.receiptType isPunched:isPunched];
        return cell;
    } else if (indexPath.row == 1) {
        MGBaseBorderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGBaseBorderDetailCell"];
        
        NSString *account = @"请选择账户";
        if (self.dataModel.accountUniqueId != 0) {
            MGAccountModel *accountModel = [MGAccountAccessor.shared getAccountModelWithUniqueId:self.dataModel.accountUniqueId];
            account = accountModel.name;
        }
        
        [cell configViewWithCornerType:MGCornerTypeTop];
        [cell configViewWithTitleValue:@"账户" detailValue:account iconName:@"ico_common_card"];
        return cell;
    } else if (indexPath.row == 2) {
        MGBaseBorderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGBaseBorderDetailCell"];
        
        NSString *categoryName = @"请选择分类";
        if (self.dataModel.categoryUniqueId != 0) {
            MGCategoryModel *categoryModel = [MGCategoryAccessor.shared getCategoryModelWithUniqueId:self.dataModel.categoryUniqueId];
            categoryName = categoryModel.name;
        }
        
        [cell configViewWithCornerType:MGCornerTypeCenter];
        [cell configViewWithTitleValue:@"分类" detailValue:categoryName iconName:@"ico_common_cate"];
        return cell;
    } else if (indexPath.row == 3) {
        MGBaseBorderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGBaseBorderDetailCell"];
        
        NSString *date = nil;
        if (self.dataModel.dateOrTime) {
            date = [[NSDate dateWithTimeIntervalSince1970:self.dataModel.actualSaveTime] toStringWithFormatter:@"M月d日"];
        } else {
            date = [[NSDate dateWithTimeIntervalSince1970:self.dataModel.actualSaveTime] toStringWithFormatter:@"M月d日 HH:mm"];
        }
        
        [cell configViewWithCornerType:MGCornerTypeBottom];
        [cell configViewWithTitleValue:@"日期" detailValue:date iconName:@"ico_common_date"];
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        if (!CGAffineTransformEqualToTransform(CGAffineTransformIdentity, self.keyboardView.transform)) {
            [self handleKeyboardTransform];
        }
    } else if (indexPath.row == 1) {
        [self handleSelectAccount];
    } else if (indexPath.row == 2) {
        [self handleSelectCategory];
    } else if (indexPath.row == 3) {
        [self handleSelectDate];
    }
}

- (void)handleKeyboardTransform {
    [UIView animateWithDuration:0.2f animations:^{
        if (CGAffineTransformEqualToTransform(CGAffineTransformIdentity, self.keyboardView.transform)) {
            self.keyboardView.transform = CGAffineTransformMakeTranslation(0, CGRectGetHeight(self.keyboardView.frame));
        } else {
            self.keyboardView.transform = CGAffineTransformIdentity;
        }
    }];
}

- (void)handleCalculateWithString:(NSString *)string {
    if ([string isEqualToString:@"C"]) {
        if (self.calculateString.length != 0) {
            self.calculateString = [self.calculateString substringToIndex:self.calculateString.length - 1];
            
            if (self.calculateString.length == 0) {
                self.calculateString = nil;
            }
        }
    } else {
        // 第一个数字不能是符号
        if ([string containsSymbol] && self.calculateString == nil) {
            
        } else {
            if (!self.calculateString) {
                self.calculateString = string;
            } else {
                // 不能连续输入两个..
                if ([string isEqualToString:@"."]) {
                    if (self.calculateString.length > 0) {
                        NSString *lastString = [self.calculateString substringFromIndex:self.calculateString.length - 1];
                        if ([lastString isEqualToString:@"."]) {
                            
                        } else {
                            self.calculateString = [self.calculateString stringByAppendingString:string];
                        }
                    }
                } else {
                    // 如果上一个是符号，并且该字符也是符号，则直接替换
                    NSString *lastString = [self.calculateString substringFromIndex:self.calculateString.length - 1];
                    if ([lastString containsSymbol] && [string containsSymbol]) {
                        NSString *sub = [self.calculateString substringToIndex:self.calculateString.length - 1];
                        self.calculateString = [sub stringByAppendingString:string];
                    } else {
                        self.calculateString = [self.calculateString stringByAppendingString:string];
                    }
                }
            }
        }
    }

    NSDecimalNumber *number = [[NSDecimalNumber alloc] initWithFloat:[self.calculateString calculateData]];
    self.dataModel.savedMoney = number;
    [self.tableView reloadData];
}

- (UIEdgeInsets)handleEdgeInsets {
    UIEdgeInsets insets = [super handleEdgeInsets];
    insets.top += 10;
    return insets;
}

- (NSString *)customPageTitle {
    return @"打卡详情";
}

@end
